package com.yxuan.springboot.service.impl;

import com.yxuan.springboot.mapper.CommentMapper;
import com.yxuan.springboot.model.Comment;
import com.yxuan.springboot.service.CommentService;
import com.yxuan.springboot.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author zchao
 *    Comment业务层实现类
 * @date 2023-05-14 20:40:39
 */
@Service
@Transactional
public class CommentServiceImpl extends BaseServiceImpl<Comment> implements CommentService {

    @Autowired
    protected CommentMapper commentMapper;
    @Autowired
    protected UserLoginService userLoginService;

    /**
     * @methodName queryCommentNum
     * @effect: 根据资讯Id，查询每篇资讯评论的数量
     */
    @Override
    public String queryCommentNum(String information) throws Exception {
        return commentMapper.queryCommentNum(information);
    }

    /**
     * @methodName queryComment
     * @effect: 根据文章Id,查询评论和评论人姓名
     */
    @Override
    public List<Comment> queryComment(String information) throws Exception {
        //获取评论对象
        List<Comment> queryCommentList = commentMapper.queryComment(information);
        //创建一个空列表，装返回的 comment 对象
        List<Comment> returnCommentList = new ArrayList<>();

//        for (Comment comment : queryCommentList) {
//            //根据评论人iD,获取评论人手机号码
//            String phoneNumber = userLoginService.findTById(comment.getUserLogin()).getPhoneNumber();
//            //生成评论人的名称
//            String userLoginName = "用户"+phoneNumber.substring(phoneNumber.length()-4);
//            comment.setUserLogin(userLoginName);
//            //将 comment 对象添加到 returnCommentList 中
//            returnCommentList.add(comment);
//        }

        queryCommentList.parallelStream().forEach(comment -> {
            //根据评论人iD,获取评论人手机号码
            String phoneNumber = null;
            try {
                phoneNumber = userLoginService.findTById(comment.getUserLogin()).getPhoneNumber();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //生成评论人的名称
            String userLoginName = "用户" + phoneNumber.substring(phoneNumber.length() - 4);
            comment.setUserLogin(userLoginName);
            //将 comment 对象添加到 returnCommentList 中
            synchronized (returnCommentList) {
                returnCommentList.add(comment);
            }
        });
        return returnCommentList;
    }
}
